package practiceProjects.SaveAllSitesOfOpenedTabsInBrowser;

/**
 * @Project ：learn_java
 * @File ：Main.java
 * @IDE ：IntelliJ IDEA
 * @Author ：自由如风间
 * @Date ：2025/3/22 21:19
 * @Description ：For study.
 */

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class Main {
    public static void main(String[] args) {
        try {
            // 连接到 Chrome 的远程调试接口
            URL url = new URL("http://localhost:9222/json");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");

            // 读取返回的 JSON 数据
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String inputLine;
            StringBuilder response = new StringBuilder();
            while((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            // 解析 JSON 数组数据，每个对象对应一个标签页
            JSONArray tabs = new JSONArray(response.toString());

            // 获取桌面路径
            String userHome = System.getProperty("user.home");
            File desktop = new File(userHome, "Desktop");
            File outputFile = new File(desktop, "browser_tabs.txt");

            // 写入文件
            BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile));
            for (int i = 0; i < tabs.length(); i++) {
                JSONObject tab = tabs.getJSONObject(i);
                String title = tab.optString("title", "无标题");
                String tabUrl = tab.optString("url", "无网址");
                writer.write("标题: " + title + "\n");
                writer.write("网址: " + tabUrl + "\n\n");
            }
            writer.close();
            System.out.println("数据已保存到: " + outputFile.getAbsolutePath());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
